import datetime
from queue import Queue

from libs.StockBase import StockBase
from libs.Objects import Objects
import pandas as pd


class StockTradingData():

    def __init__(self, tradingDate, stock, queue):
        self.tradingDate = tradingDate
        self.stock = stock
        self.queue = queue

    def download(self):
        result = self.__getTradingData(startDay=self.tradingDate, endDay=self.tradingDate, stock=self.stock)

        self.queue.put(result)
        if self.queue.qsize() % 100 == 0:
            print("%s %s %s" % (str(datetime.datetime.today().isoformat()), str(self.queue.qsize()), self.stock))

    def __getTradingData(self, startDay, endDay, stock):
        if Objects.isEmpty(startDay) or Objects.isEmpty(endDay):
            raise Exception("startDay or endDay is empty")
        # must use new connection
        bs = StockBase.getBaostock()
        rs = bs.query_history_k_data_plus(stock,
                                          "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST",
                                          start_date=startDay,
                                          end_date=endDay,
                                          frequency="d",
                                          adjustflag="3")

        data_list = []
        while (rs.error_code == '0') & rs.next():
            # 获取一条记录，将记录合并在一起
            data_list.append(rs.get_row_data())
        result = pd.DataFrame(data_list, columns=rs.fields)
        return result


if __name__ == '__main__':
    queue = Queue()
    StockTradingData('2025-02-05', 'sz.300059', queue).download()
    df_arry = [queue.get() for i in range(queue.qsize())]
    print(df_arry)
